"""
Cultural Adaptation System for Cross-Temporal Dialogue.

This module implements culture-specific communication pattern adaptation,
historical period appropriate language, and cross-cultural dialogue facilitation.
"""

import numpy as np
import logging
from typing import Dict, List, Optional, Tuple, Any, Union
from dataclasses import dataclass, field
from enum import Enum
import asyncio
import re
from collections import defaultdict

from ..personality.models import PersonalityVector, CulturalDimensions

logger = logging.getLogger(__name__)


class CommunicationStyle(Enum):
    """Communication style patterns."""
    DIRECT = "direct"
    INDIRECT = "indirect"
    FORMAL = "formal"
    INFORMAL = "informal"
    HIERARCHICAL = "hierarchical"
    EGALITARIAN = "egalitarian"


class LanguageRegister(Enum):
    """Language register levels."""
    INTIMATE = "intimate"
    CASUAL = "casual"
    CONSULTATIVE = "consultative"
    FORMAL = "formal"
    FROZEN = "frozen"


@dataclass
class CulturalContext:
    """Cultural context for dialogue adaptation."""
    primary_culture: str
    secondary_cultures: List[str] = field(default_factory=list)
    social_hierarchy: Dict[str, float] = field(default_factory=dict)
    communication_norms: Dict[str, Any] = field(default_factory=dict)
    taboo_topics: List[str] = field(default_factory=list)
    honorifics: Dict[str, str] = field(default_factory=dict)
    greeting_patterns: List[str] = field(default_factory=list)
    politeness_markers: List[str] = field(default_factory=list)


@dataclass
class AdaptationRule:
    """Rule for cultural adaptation."""
    source_pattern: str
    target_pattern: str
    cultural_dimension: str
    confidence: float
    context_requirements: List[str] = field(default_factory=list)
    explanation: str = ""


@dataclass
class AdaptationResult:
    """Result of cultural adaptation."""
    adapted_text: str
    original_text: str
    authenticity_score: float
    applied_rules: List[AdaptationRule]
    cultural_markers: List[str]
    suggested_improvements: List[str] = field(default_factory=list)
    metadata: Dict[str, Any] = field(default_factory=dict)


class CulturalAdapter:
    """
    Cultural adaptation system for authentic historical dialogue.
    
    Features:
    - Culture-specific communication pattern adaptation
    - Historical period appropriate language and expressions
    - Social norm and etiquette integration
    - Cross-cultural dialogue facilitation
    """
    
    def __init__(self):
        """Initialize cultural adapter."""
        self.cultural_patterns = self._initialize_cultural_patterns()
        self.historical_registers = self._initialize_historical_registers()
        self.social_norms = self._initialize_social_norms()
        self.communication_styles = self._initialize_communication_styles()
        
        # Adaptation rules organized by culture and time period
        self.adaptation_rules = self._initialize_adaptation_rules()
        
        # Performance tracking
        self.adaptation_stats = {
            'total_adaptations': 0,
            'successful_adaptations': 0,
            'average_authenticity_score': 0.0,
            'adaptations_by_culture': defaultdict(int),
            'rules_applied_count': defaultdict(int)
        }
        
        logger.info("CulturalAdapter initialized")
    
    def _initialize_cultural_patterns(self) -> Dict[str, Dict]:
        """Initialize culture-specific patterns and characteristics."""
        return {
            'western_medieval': {
                'time_period': (800, 1500),
                'hierarchy': 'strict',
                'communication_style': 'formal',
                'honorifics': ['my lord', 'my lady', 'sire', 'your grace'],
                'greeting_patterns': [
                    'Good morrow, {title}',
                    'I bid thee welcome',
                    'Well met, good {title}'
                ],
                'politeness_markers': ['prithee', 'if it please', 'by your leave'],
                'taboo_topics': ['questioning authority', 'heretical thoughts'],
                'characteristic_phrases': [
                    'God willing', 'by the saints', 'marry', 'forsooth'
                ]
            },
            'renaissance_italian': {
                'time_period': (1300, 1600),
                'hierarchy': 'moderate',
                'communication_style': 'expressive',
                'honorifics': ['signore', 'madonna', 'maestro'],
                'greeting_patterns': [
                    'Salve, {title}',
                    'Buongiorno, {title}',
                    'Pace e bene'
                ],
                'characteristic_phrases': [
                    'per favore', 'bene', 'eccellente', 'magnifico'
                ]
            },
            'ancient_greek': {
                'time_period': (-800, 600),
                'hierarchy': 'democratic',
                'communication_style': 'philosophical',
                'honorifics': ['citizen', 'philosopher', 'teacher'],
                'greeting_patterns': [
                    'Χαίρε (Chaire)',
                    'Peace be with you',
                    'Greetings, friend'
                ],
                'characteristic_phrases': [
                    'by Zeus', 'the gods willing', 'in truth', 'wisdom teaches'
                ]
            },
            'ancient_roman': {
                'time_period': (-753, 476),
                'hierarchy': 'strict',
                'communication_style': 'formal',
                'honorifics': ['dominus', 'senator', 'citizen', 'consul'],
                'greeting_patterns': [
                    'Ave, {title}',
                    'Salve',
                    'Vale'
                ],
                'characteristic_phrases': [
                    'by Jupiter', 'for the glory of Rome', 'pax romana'
                ]
            },
            'victorian_english': {
                'time_period': (1837, 1901),
                'hierarchy': 'strict',
                'communication_style': 'formal',
                'honorifics': ['sir', 'madam', 'your lordship', 'miss', 'mrs'],
                'greeting_patterns': [
                    'Good day, {title}',
                    'How do you do, {title}',
                    'I am delighted to make your acquaintance'
                ],
                'politeness_markers': [
                    'if I may be so bold', 'with your permission', 
                    'I beg your pardon', 'most humbly'
                ],
                'characteristic_phrases': [
                    'rather', 'quite', 'indeed', 'most certainly',
                    'I dare say', 'by Jove'
                ]
            },
            'chinese_imperial': {
                'time_period': (-221, 1912),
                'hierarchy': 'very_strict',
                'communication_style': 'indirect',
                'honorifics': ['your majesty', 'your excellency', 'master', 'elder'],
                'greeting_patterns': [
                    'This humble one greets you',
                    'Ten thousand years to you',
                    'May your wisdom shine'
                ],
                'politeness_markers': [
                    'this unworthy one', 'if heaven permits',
                    'with deepest respect', 'in your infinite wisdom'
                ],
                'characteristic_phrases': [
                    'the mandate of heaven', 'harmony under heaven',
                    'as the ancients say', 'virtue guides'
                ]
            }
        }
    
    def _initialize_historical_registers(self) -> Dict[str, Dict]:
        """Initialize historical language registers by time period."""
        return {
            'archaic_english': {
                'period': (1066, 1500),
                'pronouns': {'you': 'thou', 'your': 'thy', 'yours': 'thine'},
                'verbs': {'have': 'hast', 'do': 'dost', 'are': 'art'},
                'contractions': {'cannot': 'canst not', 'will not': 'wilt not'},
                'vocabulary': {
                    'yes': 'aye', 'before': 'ere', 'if': 'an',
                    'often': 'oft', 'from': 'from', 'know': 'ken'
                }
            },
            'early_modern_english': {
                'period': (1500, 1700),
                'characteristics': [
                    'formal sentence structure',
                    'elaborate courtesy',
                    'biblical references'
                ],
                'vocabulary': {
                    'think': 'methinks', 'nothing': 'naught',
                    'perhaps': 'mayhap', 'here': 'hither'
                }
            },
            'classical_latin_influence': {
                'period': (1300, 1600),
                'characteristics': [
                    'complex sentence structure',
                    'latin loan words',
                    'formal rhetoric'
                ],
                'phrases': [
                    'et cetera', 'per se', 'prima facie',
                    'sine qua non', 'ad infinitum'
                ]
            }
        }
    
    def _initialize_social_norms(self) -> Dict[str, Dict]:
        """Initialize social norms and etiquette by culture and period."""
        return {
            'medieval_european': {
                'gender_roles': {
                    'male': ['warrior', 'lord', 'merchant', 'cleric'],
                    'female': ['lady', 'maiden', 'mother', 'nun']
                },
                'social_classes': ['nobility', 'clergy', 'peasantry'],
                'interaction_rules': {
                    'nobility_peasant': 'formal_hierarchical',
                    'clergy_laity': 'respectful_formal',
                    'same_class': 'familiar_formal'
                },
                'conversational_taboos': [
                    'questioning divine right',
                    'criticizing nobility directly',
                    'discussing theology as layperson'
                ]
            },
            'ancient_athenian': {
                'gender_roles': {
                    'male': ['citizen', 'philosopher', 'politician', 'warrior'],
                    'female': ['wife', 'hetaira', 'priestess']
                },
                'social_classes': ['citizens', 'metics', 'slaves'],
                'interaction_rules': {
                    'citizen_citizen': 'democratic_equal',
                    'citizen_metic': 'respectful_superior',
                    'citizen_slave': 'authoritative'
                },
                'conversational_encouraged': [
                    'philosophical discussion',
                    'political debate',
                    'rhetoric and logic'
                ]
            },
            'victorian_british': {
                'gender_roles': {
                    'male': ['gentleman', 'professional', 'tradesman'],
                    'female': ['lady', 'governess', 'domestic']
                },
                'social_classes': ['upper', 'middle', 'working'],
                'interaction_rules': {
                    'cross_gender': 'extremely_formal',
                    'same_class': 'politely_formal',
                    'different_class': 'hierarchical_formal'
                },
                'conversational_taboos': [
                    'personal finances',
                    'intimate relations',
                    'bodily functions',
                    'controversial politics'
                ]
            }
        }
    
    def _initialize_communication_styles(self) -> Dict[str, Dict]:
        """Initialize communication style patterns by culture."""
        return {
            'high_context': {
                'cultures': ['chinese', 'japanese', 'arabic', 'native_american'],
                'characteristics': [
                    'indirect communication',
                    'implicit meaning',
                    'relationship focus',
                    'non-verbal emphasis'
                ],
                'patterns': {
                    'disagreement': 'I understand your position, however...',
                    'refusal': 'That would be quite difficult...',
                    'criticism': 'Perhaps there might be another way...'
                }
            },
            'low_context': {
                'cultures': ['german', 'scandinavian', 'anglo_american'],
                'characteristics': [
                    'direct communication',
                    'explicit meaning',
                    'task focus',
                    'verbal emphasis'
                ],
                'patterns': {
                    'disagreement': 'I disagree with that point',
                    'refusal': 'No, that is not possible',
                    'criticism': 'This approach has problems'
                }
            },
            'hierarchical': {
                'cultures': ['confucian', 'traditional_islamic', 'feudal'],
                'characteristics': [
                    'status-conscious language',
                    'formal address patterns',
                    'deference markers',
                    'authority respect'
                ],
                'patterns': {
                    'to_superior': 'With your permission, most honored one...',
                    'to_equal': 'My esteemed colleague...',
                    'to_subordinate': 'I direct you to...'
                }
            }
        }
    
    def _initialize_adaptation_rules(self) -> Dict[str, List[AdaptationRule]]:
        """Initialize adaptation rules organized by culture and context."""
        rules = defaultdict(list)
        
        # Medieval European rules
        rules['western_medieval'].extend([
            AdaptationRule(
                source_pattern=r'\bhello\b',
                target_pattern='Good morrow',
                cultural_dimension='greeting',
                confidence=0.9,
                explanation='Medieval greeting adaptation'
            ),
            AdaptationRule(
                source_pattern=r'\byou\b',
                target_pattern='thou',
                cultural_dimension='pronouns',
                confidence=0.8,
                context_requirements=['informal', 'equal_status'],
                explanation='Archaic pronoun usage'
            ),
            AdaptationRule(
                source_pattern=r'\byes\b',
                target_pattern='aye',
                cultural_dimension='vocabulary',
                confidence=0.7,
                explanation='Period-appropriate affirmation'
            )
        ])
        
        # Victorian English rules
        rules['victorian_english'].extend([
            AdaptationRule(
                source_pattern=r'\bhello\b',
                target_pattern='Good day',
                cultural_dimension='greeting',
                confidence=0.9,
                explanation='Victorian formal greeting'
            ),
            AdaptationRule(
                source_pattern=r'\bokay\b',
                target_pattern='very well',
                cultural_dimension='vocabulary',
                confidence=0.8,
                explanation='Formal agreement expression'
            ),
            AdaptationRule(
                source_pattern=r'\bawesome\b',
                target_pattern='most remarkable',
                cultural_dimension='vocabulary',
                confidence=0.9,
                explanation='Period-appropriate superlative'
            )
        ])
        
        # Ancient Greek rules
        rules['ancient_greek'].extend([
            AdaptationRule(
                source_pattern=r'\bhello\b',
                target_pattern='Greetings, friend',
                cultural_dimension='greeting',
                confidence=0.8,
                explanation='Classical Greek greeting'
            ),
            AdaptationRule(
                source_pattern=r'\bwisdom\b',
                target_pattern='sophia',
                cultural_dimension='vocabulary',
                confidence=0.7,
                context_requirements=['philosophical'],
                explanation='Classical philosophical terminology'
            )
        ])
        
        return dict(rules)
    
    async def adapt_context(
        self,
        context: 'DialogueContext',
        personality: PersonalityVector
    ) -> 'DialogueContext':
        """
        Adapt dialogue context for cultural authenticity.
        
        Args:
            context: Original dialogue context
            personality: Speaker's personality vector
            
        Returns:
            Culturally adapted context
        """
        # Determine primary culture from context and personality
        primary_culture = self._determine_primary_culture(context, personality)
        
        # Get cultural patterns for the identified culture
        cultural_patterns = self.cultural_patterns.get(primary_culture, {})
        
        # Adapt context elements
        adapted_context = context
        
        # Adapt language style based on cultural norms
        if 'communication_style' in cultural_patterns:
            adapted_context.language_style = cultural_patterns['communication_style']
        
        # Adapt formality level based on hierarchy
        if 'hierarchy' in cultural_patterns:
            hierarchy_level = cultural_patterns['hierarchy']
            if hierarchy_level == 'strict':
                adapted_context.formality_level = min(0.9, adapted_context.formality_level + 0.2)
            elif hierarchy_level == 'very_strict':
                adapted_context.formality_level = 0.95
            elif hierarchy_level == 'democratic':
                adapted_context.formality_level = max(0.3, adapted_context.formality_level - 0.2)
        
        # Add cultural context information
        adapted_context.cultural_context = primary_culture
        
        return adapted_context
    
    def _determine_primary_culture(
        self,
        context: 'DialogueContext',
        personality: PersonalityVector
    ) -> str:
        """Determine primary culture from context and personality."""
        # Use time period and location to determine culture
        time_period = context.time_period_start
        location = context.location.lower()
        
        # Simple mapping based on time and place
        if 800 <= time_period <= 1500 and 'europe' in location:
            return 'western_medieval'
        elif 1300 <= time_period <= 1600 and 'ital' in location:
            return 'renaissance_italian'
        elif -800 <= time_period <= 600 and 'greece' in location:
            return 'ancient_greek'
        elif -753 <= time_period <= 476 and 'rome' in location:
            return 'ancient_roman'
        elif 1837 <= time_period <= 1901 and ('england' in location or 'britain' in location):
            return 'victorian_english'
        elif -221 <= time_period <= 1912 and 'chin' in location:
            return 'chinese_imperial'
        else:
            # Default fallback
            return 'western_medieval'
    
    async def adapt_dialogue(
        self,
        text: str,
        context: 'DialogueContext',
        personality: PersonalityVector
    ) -> AdaptationResult:
        """
        Adapt dialogue text for cultural authenticity.
        
        Args:
            text: Original dialogue text
            context: Dialogue context
            personality: Speaker personality
            
        Returns:
            Adaptation result with culturally adapted text
        """
        original_text = text
        adapted_text = text
        applied_rules = []
        cultural_markers = []
        
        # Determine cultural adaptation rules to apply
        primary_culture = context.cultural_context or self._determine_primary_culture(context, personality)
        rules = self.adaptation_rules.get(primary_culture, [])
        
        # Apply adaptation rules
        for rule in rules:
            if self._should_apply_rule(rule, context, personality):
                adapted_text = re.sub(
                    rule.source_pattern,
                    rule.target_pattern,
                    adapted_text,
                    flags=re.IGNORECASE
                )
                applied_rules.append(rule)
                cultural_markers.append(rule.target_pattern)
        
        # Apply cultural communication style
        adapted_text = await self._apply_communication_style(
            adapted_text, primary_culture, context
        )
        
        # Add cultural markers and phrases
        adapted_text = self._add_cultural_markers(
            adapted_text, primary_culture, context
        )
        
        # Calculate authenticity score
        authenticity_score = self._calculate_authenticity_score(
            adapted_text, primary_culture, applied_rules
        )
        
        # Generate improvement suggestions
        suggestions = self._generate_improvement_suggestions(
            adapted_text, primary_culture, context
        )
        
        # Update statistics
        self._update_adaptation_stats(primary_culture, authenticity_score, applied_rules)
        
        return AdaptationResult(
            adapted_text=adapted_text,
            original_text=original_text,
            authenticity_score=authenticity_score,
            applied_rules=applied_rules,
            cultural_markers=cultural_markers,
            suggested_improvements=suggestions,
            metadata={
                'primary_culture': primary_culture,
                'formality_level': context.formality_level,
                'rules_applied_count': len(applied_rules)
            }
        )
    
    def _should_apply_rule(
        self,
        rule: AdaptationRule,
        context: 'DialogueContext',
        personality: PersonalityVector
    ) -> bool:
        """Determine if an adaptation rule should be applied."""
        # Check context requirements
        for requirement in rule.context_requirements:
            if requirement == 'informal' and context.formality_level > 0.7:
                return False
            elif requirement == 'formal' and context.formality_level < 0.5:
                return False
            elif requirement == 'philosophical' and 'philosophy' not in context.topic.lower():
                return False
        
        # Check personality compatibility
        if (rule.cultural_dimension == 'hierarchy' and 
            personality.cultural_dimensions.power_distance < 0.5):
            return False
        
        return True
    
    async def _apply_communication_style(
        self,
        text: str,
        culture: str,
        context: 'DialogueContext'
    ) -> str:
        """Apply culture-specific communication style patterns."""
        # Determine communication style category
        style_category = self._get_communication_style_category(culture)
        
        if style_category not in self.communication_styles:
            return text
        
        style_patterns = self.communication_styles[style_category]['patterns']
        
        # Apply style-specific transformations
        adapted_text = text
        
        # Example transformations based on style
        if style_category == 'high_context':
            # Make statements more indirect
            adapted_text = re.sub(
                r'\bI disagree\b',
                'I see your point, though perhaps...',
                adapted_text,
                flags=re.IGNORECASE
            )
        elif style_category == 'hierarchical':
            # Add deference markers based on formality
            if context.formality_level > 0.8:
                adapted_text = 'With great respect, ' + adapted_text
        
        return adapted_text
    
    def _get_communication_style_category(self, culture: str) -> str:
        """Get communication style category for a culture."""
        # Map cultures to communication style categories
        high_context_cultures = ['chinese_imperial', 'japanese_traditional']
        hierarchical_cultures = ['western_medieval', 'chinese_imperial', 'ancient_roman']
        
        if culture in high_context_cultures:
            return 'high_context'
        elif culture in hierarchical_cultures:
            return 'hierarchical'
        else:
            return 'low_context'
    
    def _add_cultural_markers(
        self,
        text: str,
        culture: str,
        context: 'DialogueContext'
    ) -> str:
        """Add cultural markers and characteristic phrases."""
        if culture not in self.cultural_patterns:
            return text
        
        patterns = self.cultural_patterns[culture]
        
        # Add characteristic phrases occasionally (probabilistic)
        if 'characteristic_phrases' in patterns and np.random.random() < 0.3:
            phrase = np.random.choice(patterns['characteristic_phrases'])
            # Add at natural pause points
            if ',' in text:
                text = text.replace(',', f', {phrase},', 1)
            else:
                text += f', {phrase}'
        
        # Add honorifics if appropriate
        if context.formality_level > 0.7 and 'honorifics' in patterns:
            # This would implement more sophisticated honorific insertion
            pass
        
        return text
    
    def _calculate_authenticity_score(
        self,
        text: str,
        culture: str,
        applied_rules: List[AdaptationRule]
    ) -> float:
        """Calculate cultural authenticity score."""
        base_score = 0.5  # Neutral baseline
        
        # Boost score for applied rules
        rule_boost = len(applied_rules) * 0.1
        base_score += rule_boost
        
        # Check for cultural markers
        if culture in self.cultural_patterns:
            patterns = self.cultural_patterns[culture]
            
            # Look for characteristic phrases
            if 'characteristic_phrases' in patterns:
                for phrase in patterns['characteristic_phrases']:
                    if phrase.lower() in text.lower():
                        base_score += 0.05
            
            # Look for appropriate honorifics
            if 'honorifics' in patterns:
                for honorific in patterns['honorifics']:
                    if honorific.lower() in text.lower():
                        base_score += 0.05
        
        # Penalty for modern anachronisms
        modern_terms = ['okay', 'cool', 'awesome', 'dude', 'guy']
        for term in modern_terms:
            if term.lower() in text.lower():
                base_score -= 0.1
        
        return max(0.0, min(1.0, base_score))
    
    def _generate_improvement_suggestions(
        self,
        text: str,
        culture: str,
        context: 'DialogueContext'
    ) -> List[str]:
        """Generate suggestions for improving cultural authenticity."""
        suggestions = []
        
        # Check for missing cultural elements
        if culture in self.cultural_patterns:
            patterns = self.cultural_patterns[culture]
            
            # Suggest adding honorifics if formal
            if (context.formality_level > 0.7 and 
                'honorifics' in patterns and
                not any(h in text.lower() for h in patterns['honorifics'])):
                suggestions.append(f"Consider adding appropriate honorifics for {culture}")
            
            # Suggest characteristic phrases
            if ('characteristic_phrases' in patterns and
                not any(p in text.lower() for p in patterns['characteristic_phrases'])):
                suggestions.append(f"Could enhance with characteristic {culture} expressions")
        
        # Check for modern language
        modern_indicators = ['ok', 'yeah', 'stuff', 'thing']
        if any(term in text.lower() for term in modern_indicators):
            suggestions.append("Consider replacing modern colloquialisms with period-appropriate language")
        
        return suggestions
    
    def _update_adaptation_stats(
        self,
        culture: str,
        authenticity_score: float,
        applied_rules: List[AdaptationRule]
    ):
        """Update adaptation statistics."""
        self.adaptation_stats['total_adaptations'] += 1
        
        if authenticity_score >= 0.7:
            self.adaptation_stats['successful_adaptations'] += 1
        
        # Update running average
        total = self.adaptation_stats['total_adaptations']
        self.adaptation_stats['average_authenticity_score'] = (
            (self.adaptation_stats['average_authenticity_score'] * (total - 1) + 
             authenticity_score) / total
        )
        
        # Track by culture
        self.adaptation_stats['adaptations_by_culture'][culture] += 1
        
        # Track rule usage
        for rule in applied_rules:
            rule_key = f"{rule.cultural_dimension}:{rule.source_pattern}"
            self.adaptation_stats['rules_applied_count'][rule_key] += 1
    
    async def suggest_corrections(
        self,
        text: str,
        context: 'DialogueContext'
    ) -> List[Dict[str, str]]:
        """Suggest cultural corrections for dialogue text."""
        corrections = []
        
        # Identify primary culture
        primary_culture = context.cultural_context or 'western_medieval'
        
        # Find inappropriate elements
        modern_terms = {
            'okay': 'very well',
            'cool': 'excellent',
            'awesome': 'remarkable',
            'dude': 'fellow',
            'guy': 'man'
        }
        
        for modern, replacement in modern_terms.items():
            if modern in text.lower():
                corrections.append({
                    'type': 'replacement',
                    'original': modern,
                    'replacement': replacement,
                    'explanation': f"'{modern}' is anachronistic for {primary_culture}",
                    'confidence': 0.9
                })
        
        return corrections
    
    async def calculate_authenticity(
        self,
        text: str,
        context: 'DialogueContext',
        personality: PersonalityVector
    ) -> float:
        """Calculate cultural authenticity score for dialogue text."""
        primary_culture = context.cultural_context or self._determine_primary_culture(context, personality)
        
        # Use existing authenticity calculation
        return self._calculate_authenticity_score(text, primary_culture, [])
    
    def get_performance_metrics(self) -> Dict[str, Any]:
        """Get adapter performance metrics."""
        return self.adaptation_stats.copy()
    
    def add_cultural_pattern(
        self,
        culture: str,
        pattern_data: Dict[str, Any]
    ):
        """Add custom cultural pattern."""
        self.cultural_patterns[culture] = pattern_data
        logger.info(f"Added cultural pattern for {culture}")
    
    def add_adaptation_rule(
        self,
        culture: str,
        rule: AdaptationRule
    ):
        """Add custom adaptation rule."""
        self.adaptation_rules[culture].append(rule)
        logger.info(f"Added adaptation rule for {culture}: {rule.source_pattern} -> {rule.target_pattern}")
    
    def reset_stats(self):
        """Reset adaptation statistics."""
        self.adaptation_stats = {
            'total_adaptations': 0,
            'successful_adaptations': 0,
            'average_authenticity_score': 0.0,
            'adaptations_by_culture': defaultdict(int),
            'rules_applied_count': defaultdict(int)
        }
        logger.info("Adaptation statistics reset")